package com.example.demo28_cas_client1.config;

import org.jasig.cas.client.session.SingleSignOutFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.cas.authentication.CasAuthenticationProvider;
import org.springframework.security.cas.web.CasAuthenticationEntryPoint;
import org.springframework.security.cas.web.CasAuthenticationFilter;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.authentication.logout.LogoutFilter;

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    CasAuthenticationProvider casAuthenticationProvider;
    @Autowired
    CasAuthenticationEntryPoint casAuthenticationEntryPoint;
    @Autowired
    CasAuthenticationFilter casAuthenticationFilter;
    @Autowired
    SingleSignOutFilter singleSignOutFilter;
    @Autowired
    LogoutFilter logoutFilter;

    /**
     * 首先配置 authenticationProvider，这个 authenticationProvider 实际上就是一开始配置的 CasAuthenticationProvider。
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(casAuthenticationProvider);
    }

    /**
     * 接下来配置 /user/** 格式的路径需要有 user 角色才能访问，登录路径 /login/cas 可以直接访问
     * ，剩余接口都是登录成功之后才能访问。
     * 最后把 authenticationEntryPoint 配置进来，再把自定义的过滤器加进来，这些都比较容易我就不多说了。
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/admin/**").hasRole("admin")
                .antMatchers("/user/**").hasRole("user")
                .antMatchers("/login/cas").permitAll()
                .anyRequest().authenticated()
                .and()
                .exceptionHandling()
                .authenticationEntryPoint(casAuthenticationEntryPoint)
                .and()
                .addFilter(casAuthenticationFilter)
                .addFilterBefore(singleSignOutFilter,CasAuthenticationFilter.class)
                .addFilterBefore(logoutFilter,LogoutFilter.class);
    }

}
